#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Attributes:
    __version__ (str): "0.0.1"
    __copyright__ (str): "Copyright (C) 2025 z"
    __license__ (str): "MIT"
    __author__ (str): "Z"
"""

import inspect
from flask import request

from wingman import db_enter, send, logger
from wingman.common.error import ErrorCode
from config.system import (PROMETHEUS_DEV_ADDR, PROMETHEUS_TEST_ADDR, PROMETHEUS_PRE_ADDR, PROMETHEUS_PROD_ADDR )

class Prometheus:
    """prometheus alertmanager消息接收,发送到钉钉/飞书及写入数据库"""

    def __check_env(self, client_ip) -> str:
        env_mapping = {
            PROMETHEUS_DEV_ADDR: "dev",
            PROMETHEUS_TEST_ADDR: "test",
            PROMETHEUS_PRE_ADDR: "pre",
            PROMETHEUS_PROD_ADDR: "prod",
        }
        return env_mapping.get(client_ip, "debug")

    def __validate_prometheus_data(self, item, message):
        # 定义验证函数
        def get_valid_value(data, key, default=""):
            return data.get(key, default) if isinstance(data, dict) else default
        # 获取labels和annotations
        label_data = get_valid_value(item, "labels", {})
        annotation_data = get_valid_value(item, "annotations", {})
        # 返回验证后的数据
        content = {
            "status": get_valid_value(item, "status"),
            "alertname": get_valid_value(label_data, "alertname"),
            "hostname": get_valid_value(label_data, "hostname"),
            "instance": get_valid_value(label_data, "instance", "").replace(":9100", ""),
            "job": get_valid_value(label_data, "job"),
            "monitor": get_valid_value(label_data, "monitor"),
            "severity": get_valid_value(label_data, "severity"),
            "description": get_valid_value(annotation_data, "description"),
            "summary": get_valid_value(annotation_data, "summary"),
            "value": get_valid_value(annotation_data, "value"),
            "group": get_valid_value(message.get("groupLabels", {}), "alertname"),
            "externalURL": get_valid_value(message, "externalURL"),
        }
        return content

    def get_prometheus(self):
        message = request.get_json()
        logger.error(000000000, message, __name__)
        client_ip = request.remote_addr
        # headers_str = request.headers
        env_name = self.__check_env(client_ip)
        function_name = inspect.currentframe().f_code.co_name  # 获取当前函数名称

        arrangement_list_dict = []
        for item in message["alerts"]:
            arrangement_list_dict.append(self.__validate_prometheus_data(item,message))

        try:
            for content_dict in arrangement_list_dict:
                content_dict.update({ 'customize_env': env_name, 'source_client_ip': client_ip })
                db_enter(content_dict, function_name, "local")
                send(content_dict, function_name)
                logger.info(ErrorCode.SUCCESS.value, content_dict, __name__)
        except Exception as e:
            logger.error(ErrorCode.PROMETHEUS_GET.value, str(e), __name__)
        finally:
            return content_dict
